package plugin.util;

import java.io.PrintStream;

import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.console.ConsolePlugin;
import org.eclipse.ui.console.IConsole;
import org.eclipse.ui.console.IConsoleFactory;
import org.eclipse.ui.console.IConsoleManager;
import org.eclipse.ui.console.IOConsoleOutputStream;
import org.eclipse.ui.console.MessageConsole;

public class ConsoleFactory implements IConsoleFactory {

	private static MessageConsole console = new MessageConsole("CODEGEN", null);

	static boolean exists = false;
	static {
		//print();
	}

	static void print() {
		while (true) {
			System.err.println(">>>>>>>>>");
		}
	}

	/**
	 * */
	public void openConsole() {
		showConsole();
	}

	/**
	 *
	 *
	 *
	 *
	 *
	 *
	 * */
	private static void showConsole() {
		if (console != null) {
			IConsoleManager manager = ConsolePlugin.getDefault()
					.getConsoleManager();

			IConsole[] existing = manager.getConsoles();
			exists = false;
			for (int i = 0; i < existing.length; i++) {
				if (console == existing[i])
					exists = true;
			}
			if (!exists) {
				manager.addConsoles(new IConsole[] { console });
			}

			 console.activate();

		}
	}

	/**
	 *
	 *
	 *
	 *
	 * */
	public static void closeConsole() {
		IConsoleManager manager = ConsolePlugin.getDefault()
				.getConsoleManager();
		if (console != null) {
			manager.removeConsoles(new IConsole[] { console });
		}
	}

	/**
	 * ����System.setOut��������������������̨
	 *
	 */
	public static void initSysOut(){
		IOConsoleOutputStream printer = ConsoleFactory.getConsole().newOutputStream();
		Display display = Display.getCurrent();
		printer.setColor(display.getSystemColor(SWT.COLOR_RED));
		//printer.setActivateOnWrite(true);
		System.setOut(new PrintStream(printer));
//		System.setErr(new PrintStream(printer));
	}
	/**
	 *
	 * @return
	 */
	public static MessageConsole getConsole() {

		showConsole();

		return console;
	}
}
